import 'dart:math';

import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/common/styles/colors.dart';

class SliderWidget extends StatelessWidget {
  const SliderWidget({
    super.key,
    required this.value,
    this.onChanged,
    this.onChangeEnd,
  });

  final RxInt value;
  final ValueChanged<double>? onChanged;
  final ValueChanged<double>? onChangeEnd;

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final gradient = onChanged == null
          ? LinearGradient(colors: [
              Color(0xFF2674FF).withAlpha(128),
              Color(0xFFA2C4EF),
            ])
          : const LinearGradient(colors: [
              Color(0xFF2674FF),
              Color(0xFFA2C4EF),
            ]);
      return SizedBox(
        width: 15.w,
        height: 247.h,
        child: RotatedBox(
          quarterTurns: 3,
          child: SliderTheme(
            data: SliderThemeData(
              trackHeight: 15.h,
              thumbShape: GradientSliderComponentShape(
                  msg: value.value.toString(),
                  rectWH: 22.r,
                  overlayRectSpace: 4,
                  overlayColor: const Color(0xFFD9D9D9),
                  thumbGradient: gradient),
              overlayShape: RoundSliderOverlayShape(overlayRadius: 16.r),
              trackShape:
                  _GradientRectSliderTrackShape(linearGradient: gradient),
              thumbColor: Colors.white,
              showValueIndicator: ShowValueIndicator.never,
              // valueIndicatorColor: const Color(0xFF2674FF),
              // valueIndicatorTextStyle: const TextStyle(
              //   color: Colors.white,
              //   fontSize: 14,
              //   fontWeight: FontWeight.bold,
              // ),
            ),
            child: Slider(
              value: value.value.toDouble(),
              min: -12,
              max: 12,
              divisions: 24,
              // label: value.value.toString(),
              onChanged: onChanged,
              onChangeEnd:onChangeEnd,
            ),
          ),
        ),
      );
    });
  }
}

/// 自定义始终显示气泡的滑块
class _AlwaysShowTooltipSlider extends StatefulWidget {
  final double value;
  final double min;
  final double max;
  final int divisions;
  final String label;
  final ValueChanged<double>? onChanged;

  const _AlwaysShowTooltipSlider({
    required this.value,
    required this.min,
    required this.max,
    required this.divisions,
    required this.label,
    this.onChanged,
  });

  @override
  State<_AlwaysShowTooltipSlider> createState() =>
      _AlwaysShowTooltipSliderState();
}

class _AlwaysShowTooltipSliderState extends State<_AlwaysShowTooltipSlider> {
  late final SliderController _controller;

  @override
  void initState() {
    super.initState();
    _controller = SliderController(this);
    // 延迟执行，确保组件已经完全构建
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _controller.showTooltip();
    });
  }

  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: _controller.link,
      child: Slider(
        value: widget.value,
        min: widget.min,
        max: widget.max,
        divisions: widget.divisions,
        label: widget.label,
        onChanged: widget.onChanged,
      ),
    );
  }
}

/// 滑块控制器，用于显示气泡
class SliderController {
  final _AlwaysShowTooltipSliderState _state;
  final LayerLink link = LayerLink();
  OverlayEntry? _overlayEntry;

  SliderController(this._state);

  void showTooltip() {
    if (_overlayEntry != null) {
      return;
    }

    final RenderBox box = _state.context.findRenderObject() as RenderBox;
    final Offset topCenter = box.size.topCenter(box.localToGlobal(Offset.zero));

    // 创建一个假的拖动事件来触发气泡显示
    final RenderObject? sliderRenderObject = _state.context.findRenderObject();
    if (sliderRenderObject != null && sliderRenderObject is RenderBox) {
      final SliderThemeData sliderTheme = SliderTheme.of(_state.context);
      // final ValueIndicatorShape valueIndicatorShape = sliderTheme.valueIndicatorShape!;

      // 使用 OverlayEntry 显示气泡
      _overlayEntry = OverlayEntry(
        builder: (BuildContext context) {
          return Positioned(
            top: topCenter.dy - 40.h, // 调整位置
            child: CompositedTransformFollower(
              link: link,
              offset: Offset(0, -40.h),
              child: Material(
                color: Colors.transparent,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: const Color(0xFF2674FF),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: RotatedBox(
                    quarterTurns: 1, // 将文字旋转90度
                    child: Text(
                      _state.widget.label,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          );
        },
      );

      Overlay.of(_state.context).insert(_overlayEntry!);
    }
  }

  void hideTooltip() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }
}

/// 自定义渐变滑块轨道形状
class _GradientRectSliderTrackShape extends SliderTrackShape {
  final LinearGradient linearGradient;

  _GradientRectSliderTrackShape({required this.linearGradient});

  @override
  Rect getPreferredRect({
    required RenderBox parentBox,
    Offset offset = Offset.zero,
    required SliderThemeData sliderTheme,
    bool isEnabled = false,
    bool isDiscrete = false,
  }) {
    final double trackHeight = sliderTheme.trackHeight ?? 0;
    final double trackLeft = offset.dx;
    final double trackTop =
        offset.dy + (parentBox.size.height - trackHeight) / 2;
    final double trackWidth = parentBox.size.width;
    return Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight);
  }

  @override
  void paint(
    PaintingContext context,
    Offset offset, {
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required Animation<double> enableAnimation,
    required Offset thumbCenter,
    Offset? secondaryOffset,
    bool isEnabled = false,
    bool isDiscrete = false,
    required TextDirection textDirection,
  }) {
    // 获取轨道区域
    final Rect trackRect = getPreferredRect(
      parentBox: parentBox,
      offset: offset,
      sliderTheme: sliderTheme,
      isEnabled: isEnabled,
      isDiscrete: isDiscrete,
    );

    // 计算激活和非激活部分
    final double trackWidth = trackRect.width;
    final double trackLeft = trackRect.left;
    final double thumbPos = thumbCenter.dx;

    // 创建渐变画笔
    final Paint activePaint = Paint()
      ..shader = linearGradient.createShader(trackRect);

    final Paint inactivePaint = Paint()..color = Colors.grey.shade300;

    // 绘制非激活部分
    final Rect inactiveTrackRect = Rect.fromLTWH(
      textDirection == TextDirection.ltr ? thumbPos : trackLeft,
      trackRect.top,
      textDirection == TextDirection.ltr
          ? (trackWidth - (thumbPos - trackLeft))
          : (thumbPos - trackLeft),
      trackRect.height,
    );

    // 绘制激活部分
    final Rect activeTrackRect = Rect.fromLTWH(
      textDirection == TextDirection.ltr ? trackLeft : thumbPos,
      trackRect.top,
      textDirection == TextDirection.ltr
          ? (thumbPos - trackLeft)
          : (trackWidth - (thumbPos - trackLeft)),
      trackRect.height,
    );

    // 绘制圆角矩形
    final RRect inactiveRRect = RRect.fromRectAndRadius(
      inactiveTrackRect,
      Radius.circular(trackRect.height / 2),
    );

    final RRect activeRRect = RRect.fromRectAndRadius(
      activeTrackRect,
      Radius.circular(trackRect.height / 2),
    );

    context.canvas.drawRRect(inactiveRRect, inactivePaint);
    context.canvas.drawRRect(activeRRect, activePaint);
  }
}

class GradientSliderComponentShape extends SliderComponentShape {
  final double rectWH;
  final double overlayRectSpace;
  final LinearGradient thumbGradient;
  final Color? overlayColor;
  final String msg;

  GradientSliderComponentShape(
      {required this.rectWH,
      required this.msg,
      required this.overlayRectSpace,
      this.thumbGradient = const LinearGradient(colors: [
        Color(0xFF2674FF),
        Color(0xFFA2C4EF),
      ]),
      this.overlayColor});

  TextPainter labelTextPainter = TextPainter()
    ..textDirection = TextDirection.ltr;

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return const Size(0, 0);
  }

  @override
  void paint(PaintingContext context, Offset center,
      {required Animation<double> activationAnimation,
      required Animation<double> enableAnimation,
      required bool isDiscrete,
      required TextPainter labelPainter,
      required RenderBox parentBox,
      required SliderThemeData sliderTheme,
      required TextDirection textDirection,
      required double value,
      required double textScaleFactor,
      required Size sizeWithOverflow}) {
    final Canvas canvas = context.canvas;
    // 点击滑块时阴影
    // canvas.drawShadow(
    //     Path()
    //       ..addRRect(RRect.fromRectAndRadius(
    //         Rect.fromCenter(center: center, width: 38, height: 34),
    //         const Radius.circular(19),
    //       )),
    //     Colors.red,
    //     5,
    //     false);
    double overlayWH = rectWH + overlayRectSpace;
    // 滑块描边
    canvas.drawRRect(
      RRect.fromRectAndRadius(
        Rect.fromCenter(center: center, width: overlayWH, height: overlayWH),
        Radius.circular(overlayWH / 2),
      ),
      Paint()
        ..color = (overlayColor != null)
            ? overlayColor!
            : const Color.fromARGB(255, 252, 241, 216),
    );
    // 滑块内
    canvas.drawRRect(
        RRect.fromRectAndRadius(
          Rect.fromCenter(center: center, width: rectWH, height: rectWH),
          Radius.circular(rectWH / 2),
        ),
        Paint()..color = const Color.fromARGB(255, 255, 255, 255));
    canvas.drawRRect(
        RRect.fromRectAndRadius(
          Rect.fromCenter(center: center, width: 12, height: 12),
          Radius.circular(rectWH / 2),
        ),
        Paint()
          ..shader = thumbGradient.createShader(
              Rect.fromCenter(center: center, width: rectWH, height: rectWH)));
    //绘制labels的文字内容
    labelTextPainter.text = TextSpan(
        text: msg,
        style: TextStyle(fontSize: 10, color: Colours.dark_text_gray));
    labelTextPainter.layout();

    // 保存当前画布状态
    canvas.save();
    // 将画布旋转90度
    canvas.translate(center.dx, center.dy - 0);
    canvas.rotate(pi / 2); // 旋转90度（π/2弧度）
    // 绘制旋转后的文本
    labelTextPainter.paint(canvas, Offset(-labelTextPainter.width / 2, -25));
    // 恢复画布状态
    canvas.restore();
  }
}
